import os
import time
import logging
from logging import handlers
from squirrel_core.commons.utils.get_config import get_config

log_path = os.environ.get("LOG_PATH", "/")


class LoggerObject(object):

    _instance = None

    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super(LoggerObject, cls).__new__(cls)
            return cls._instance
        return cls._instance

    def __init__(self, filename=""):
        self.log_setting = get_config(file_name='base_config', sections='log_save')
        self.stream_flag = self.log_setting.get("stream_flag", True)
        self.file_flag = self.log_setting.get("file_flag", True)
        self.pid = os.getpid()
        self.dirpath = os.path.join(log_path, f"squirrel_core/{filename}")
        self.job_id = os.environ.get("JOB_ID", "")
        filename = f"{filename}_{self.job_id}_{self.pid}_{int(time.time())}"
        self.filepath = ''.join([self.dirpath, f'/{filename}.log'])
        self.logger = logging.getLogger(self.dirpath)
        self.format_str = logging.Formatter(f'%(asctime)s-%(filename)s-line:%(lineno)d-%(levelname)s:%(message)s')
        self.setLogger()
        self.logger.propagate = False

    def setLogger(self):
        if self.logger.handlers:
            return self.logger
        if self.stream_flag:
            th = self.setStreamLogger()
            self.logger.addHandler(th)
        if self.file_flag:
            fl = self.setFileLogger()
            self.logger.addHandler(fl)
        self.logger.setLevel(logging.INFO)
        return self.logger

    def setFileLogger(self):
        if not os.path.isdir(self.dirpath):
            os.makedirs(self.dirpath)
        backup_count = 3
        th = handlers.TimedRotatingFileHandler(filename=self.filepath, when='midnight', interval=1, backupCount=backup_count,
                                               encoding='utf-8')
        th.suffix = '%Y-%m-%d'
        th.setFormatter(self.format_str)
        return th

    def setStreamLogger(self):
        sh = logging.StreamHandler()
        sh.setFormatter(self.format_str)
        return sh


def Logging(name=''):
    name = name or os.getenv(key='spider_name', default='spider')
    log = LoggerObject(name)
    return log.logger


if __name__ == '__main__':
    logger = Logging()